package juc.scenarios.startup.service.impl;

import juc.scenarios.startup.model.ServiceStatus;
import juc.scenarios.startup.service.HealthCheckService;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 数据库健康检查服务
 */
public class DatabaseHealthCheckService implements HealthCheckService {
    
    private static final String SERVICE_NAME = "数据库服务";
    private static final Random RANDOM = new Random();
    
    @Override
    public ServiceStatus checkHealth() {
        LocalDateTime startTime = LocalDateTime.now();
        
        try {
            // 模拟数据库连接检查
            ServiceStatus.ServiceState state = performDatabaseCheck();
            
            LocalDateTime endTime = LocalDateTime.now();
            long duration = java.time.Duration.between(startTime, endTime).toMillis();
            

            return ServiceStatus.builder()
                    .serviceName(SERVICE_NAME)
                    .state(state)
                    .message(state == ServiceStatus.ServiceState.HEALTHY ? "数据库连接正常" : "数据库连接异常")
                    .startTime(startTime)
                    .endTime(endTime)
                    .duration(duration)
                    .build();
                    
        } catch (Exception e) {
            LocalDateTime endTime = LocalDateTime.now();
            long duration = java.time.Duration.between(startTime, endTime).toMillis();
            
            return ServiceStatus.builder()
                    .serviceName(SERVICE_NAME)
                    .state(ServiceStatus.ServiceState.UNHEALTHY)
                    .message("数据库检查异常: " + e.getMessage())
                    .startTime(startTime)
                    .endTime(endTime)
                    .duration(duration)
                    .build();
        }
    }
    
    @Override
    public String getServiceName() {
        return SERVICE_NAME;
    }
    
    @Override
    public long getTimeout() {
        return 3000L; // 数据库检查超时时间3秒
    }
    
    /**
     * 模拟数据库检查
     */
    private ServiceStatus.ServiceState performDatabaseCheck() throws InterruptedException {
        // 模拟检查耗时（1-2秒）
        long checkTime = 1000 + RANDOM.nextInt(1000);
        TimeUnit.MILLISECONDS.sleep(checkTime);
        
        // 90%概率正常，10%概率异常
        return RANDOM.nextDouble() < 0.9 ? 
                ServiceStatus.ServiceState.HEALTHY : 
                ServiceStatus.ServiceState.UNHEALTHY;
    }
}